<template>
  <h2 style="text-align: center;">用户登录页面</h2>
  <br/>
 <el-form ref="ruleFormRef" style="max-width: 600px;margin:auto" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

    <el-form-item label="用户名" prop="userName">
      <el-input v-model="form.userName" show-word-limit />
    </el-form-item>

    <el-form-item label="密码" prop="userPwd">
      <el-input v-model="form.userPwd" show-password />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
      <el-button type="info" @click="resetForm(ruleFormRef)">取消操作</el-button>
      <el-button type="warning" @click="addUserInfo">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

import {useRoute,useRouter} from 'vue-router'

const route = useRoute();
const router = useRouter();

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const form: any = reactive({
  userName: '',
  userPwd:''
})

//校验规则
const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 30, message: '字符长度介于3-30', trigger: 'blur' },
  ],
  userPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' }, 
  ],
})

//登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let userInfoLogin = {
        userName: form.userName,
        userPwd: form.userPwd
      }
      axios.post('/api/UserManagemement/UserLogin', userInfoLogin).then(res => {
        console.log(res);
        if (res.data.data != null) {
          ElMessage.success("登录成功!")
          localStorage.Tokens = res.data.data;
          localStorage.userName = form.userName;    
          //localStorage.userPwd = form.userPwd;    
         router.push('Main')
        } else {
          ElMessage.error("登录失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//取消操作
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//注册
const addUserInfo = () => {
  router.push('AddUserInfo')
}

</script>

<style scoped>

</style>